<template>
    <div class="password-checker">
        <!-- 密码输入框 -->
        <input type="password" :value="password" placeholder="请输入密码" @input="updatePassword($event.target.value)" />

        <!-- 密码强度条 -->
        <div class="strength-bar">
            <div class="strength-bar-fill" :style="strengthBarStyle"></div>
        </div>

        <!-- 强度消息 -->
        <p>{{ strengthMessage }}</p>
    </div>
</template>

<script>
export default {
    name: "PasswordStrength",
    props: {
        modelValue: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            strengthBarStyle: {
                width: "0%",
                backgroundColor: "#ccc"
            }
        };
    },
    computed: {
        password() {
            return this.modelValue;
        }
    },
    methods: {
        updatePassword(value) {
            this.$emit("update:modelValue", value);
            this.checkPasswordStrength(value);
        },
        checkPasswordStrength(password) {
            const strength = this.calculateStrength(password);
            this.updateStrengthBar(strength);
        },
        calculateStrength(password) {
            let strength = 0;

            if (password.length >= 8) strength += 1;
            if (/[A-Z]/.test(password)) strength += 1;
            if (/[a-z]/.test(password)) strength += 1;
            if (/[0-9]/.test(password)) strength += 1;
            if (/[\W_]/.test(password)) strength += 1;

            return strength;
        },
        updateStrengthBar(strength) {
            let barWidth = "0%";
            let color = "#ccc";

            if (strength === 1) {
                barWidth = "20%";
                color = "#AC6A65";
            } else if (strength === 2) {
                barWidth = "40%";
                color = "#DD9C9D";
            } else if (strength === 3) {
                barWidth = "60%";
                color = "#f4d9bc";
            } else if (strength === 4) {
                barWidth = "80%";
                color = "#aecc99";
            } else if (strength === 5) {
                barWidth = "100%";
                color = "#679Ec1";
            }

            this.strengthBarStyle = {
                width: barWidth,
                backgroundColor: color
            };
        }
    }
};
</script>

<style scoped>
.password-checker {
    width: 90%;
}

input {
    border: none;
    outline: none;
    width: 100%;
    height: 4vw;
    font-size: 3vw;
}

.strength-bar {
    height: 1.9vw;
    padding: 1px;
    border: 1px solid #ccc;
    border-radius: 1px;
}

.strength-bar div {
    height: 100%;
    transition: width 0.2s ease-in-out;
}
</style>